package com.erp.myAdapter

import android.annotation.SuppressLint
import androidx.appcompat.app.AlertDialog
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.EditText
import com.erp.R
import com.erp.bean.JieHaoKBean
import com.erp.mclass.QuanXian
import com.erp.module.jiehao.FragmentKJieHao
import com.erp.module.jiehao.JieHaoContract
import com.erp.util.Myutil
import com.erp.util.Sputil
import kotlinx.android.synthetic.main.dialog_etshuru.*
import kotlinx.android.synthetic.main.lv_jiehao_item.view.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by Administrator on 2017/11/17/017.
 * 作者：刘洋
 */
class JieHaoKAdapter(var jiehaoList: MutableList<JieHaoKBean>, var context:Context, var jieHaoKP: JieHaoContract.JieHaoP, val fenpeisuoyou : String, val quxiaofenpei: String) : BaseAdapter(){
    var minflater: LayoutInflater = LayoutInflater.from(context)
    var sp: SharedPreferences= Sputil.sp("erp")
    var mtime= Date().time / 1000
    @SuppressLint("ViewHolder")
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var v : View=minflater.inflate(R.layout.lv_jiehao_item,null)
        val jiehao=jiehaoList[position]
        Myutil.settv(jiehao.distributed_target,v.FenPeiTv)
        Myutil.settv(getdatanoNian(jiehao.assign_time),v.TimeTv)
        Myutil.settv(jiehao.creator_name,v.ShangChuanRenTv)
        Myutil.settv(jiehao.assignment_name,v.FenPeiRenTv)
        if(sp.getBoolean(fenpeisuoyou,false)&&jiehao.is_distributed=="0"){
            v.FenPeiBt.visibility=View.VISIBLE
        }else{
            if(position==0){
                if(sp.getBoolean("isfenpeijiehao",false)) {
                    v.FenPeiBt.visibility = View.VISIBLE
                }
            }
        }
        if(jiehao.is_distributed=="1"){
            v.JieHaoLl.setBackgroundColor(Color.LTGRAY)
            v.FenPeiTv.setTextColor(Color.GRAY)
            v.JieHaoTv.setTextColor(Color.GRAY)
            v.TimeTv.setTextColor(Color.GRAY)
            if(sp.getBoolean(quxiaofenpei,false)) {
                v.FenPeiBt.visibility = View.VISIBLE
                v.FenPeiBt.text = "取消分配"
            }
        }
        if(QuanXian.isquanmingjiehao || jiehao.is_distributed=="1"){
            val ss = jiehao.batch_names.split(",")
            val sb = StringBuffer("")
            for(i in 0 until ss.size){
                sb.append(ss[i])
                if(i<ss.size-1){
                    sb.append("\n")
                }
            }
            Myutil.settv(sb.toString(), v.JieHaoTv)
        }else{
//            val ss = jiehao.batch_names.split(",")
//            val sb = StringBuffer("")
//            for(i in 0 until ss.size){
//                if(ss[i].length>3) {
//                    var a = ss[i].subSequence(0, ss[i].length - 3).toString()
//                    a = "$a***"
//                    sb.append(a)
//                    if(i<ss.size-1){
//                        sb.append("\n")
//                    }
//                }else{
//                    sb.append(ss[i])
//                    if(i<ss.size-1){
//                        sb.append("\n")
//                    }
//                }
//            }
            Myutil.settv("**********", v.JieHaoTv)
//            Myutil.settv(sb.toString(), v.JieHaoTv)
        }
        if (jiehao.assign_time.matches("[0-9]+".toRegex())&&jiehao.assign_time!="") {
            if ((mtime - jiehao.assign_time.toLong()) > 300) {
                v.NewIv.visibility = View.GONE
            } else {
                v.NewIv.visibility = View.VISIBLE
            }
        }
        if(jiehao.is_distributed=="0") {
                v.FenPeiBt.setOnClickListener {
                    var time=Date().time / 1000-sp.getLong(FragmentKJieHao.FENPEITIME,0L)
                    if(time<600){
                        var dialog=AlertDialog.Builder(context)
                        dialog.setTitle("提示")
                        dialog.setMessage("分配至少要相隔十分钟，距离再次上传还有"+getdatage(600-time)+".")
                        dialog.setPositiveButton("确定",{ dialog, which -> dialog.dismiss() })
                        dialog.setNegativeButton("取消",{ dialog, which -> dialog.dismiss() })
                        dialog.show()
                    }else {
                        val dialog = AlertDialog.Builder(context).create()
                        dialog.setView(EditText(context))
                        dialog.show()
                        dialog.setContentView(R.layout.dialog_etshuru)
                        val window = dialog.window
                        val p = window?.attributes // 获取对话框当前的参数值
                        if (p != null) {
                            p.width = (sp.getInt("width", 0) * 0.9).toInt()
                        } // 宽度设置为屏幕的0.65
                        if (window != null) {
                            window.attributes = p
                        }
                        dialog.LeftBt.setOnClickListener {
                            var s=dialog.FenPeiEt.text.toString()
                            if(s.trim()==""){
                                Myutil.MyTost("必须输入分配目标才能确定")
                            }else {
                                jieHaoKP.fenPeiJieHao(jiehaoList[position].batch_names, dialog.FenPeiEt.text.toString(), "1")
                                dialog.dismiss()
                            }
                        }
                        dialog.RightBt.setOnClickListener {
                            dialog.dismiss()
                        }
                    }
                }
        }else if(jiehao.is_distributed=="1"){
            v.FenPeiBt.setOnClickListener {
                val dialog=AlertDialog.Builder(context)
                dialog.setTitle("提示")
                dialog.setMessage("确定要取消分配吗？")
                dialog.setPositiveButton("确定") { dialog, which ->
                    jieHaoKP.fenPeiJieHao(jiehaoList[position].batch_names, "", "0")
                    dialog.dismiss()
                }
                dialog.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
                dialog.show()
            }
        }
        return v
    }

    override fun getItem(position: Int): Any = jiehaoList[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getCount(): Int = jiehaoList.size
    fun Allnotify(){
        mtime= Date().time / 1000
        notifyDataSetChanged()
    }

    //时间戳转换为MM-dd HH:mm:ss格式
    fun getdatanoNian(s: String?): String {
        if (s == null) {
            return "null"
        }
        val ss = s + ""
        if (ss.matches("[0-9]+".toRegex())) {
            if (ss != "null") {
                val format = SimpleDateFormat("MM-dd HH:mm")
                val t = java.lang.Long.valueOf(s)
                val date = Date(t!! * 1000)
                return format.format(date.time)
            }
        } else {
            return ss
        }
        return ""
    }
    fun getdatage(time : Long): String{
        var s = StringBuffer("")
        if(time>60) {
            s.append((time / 60).toInt()).append("分钟")
        }
        s.append(time%60).append("秒")
        return s.toString()
    }

}